package cn.edu.zut.score.service.impl;

import cn.edu.zut.score.core.cache.RedisCache;
import cn.edu.zut.score.core.constant.MessageTypeEnum;
import cn.edu.zut.score.core.constant.ReplyInfoStatus;
import cn.edu.zut.score.core.convert.ReplyConvert;
import cn.edu.zut.score.core.domain.PageResponse;
import cn.edu.zut.score.core.domain.RestResponse;
import cn.edu.zut.score.core.dto.request.ReplyAddRequest;
import cn.edu.zut.score.core.dto.request.ReplyPageRequest;
import cn.edu.zut.score.core.dto.response.ReplyResponse;
import cn.edu.zut.score.core.entity.*;
import cn.edu.zut.score.core.util.DateUtils;
import cn.edu.zut.score.core.util.StringUtils;
import cn.edu.zut.score.mapper.ReplyMapper;
import cn.edu.zut.score.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zby
 * @since 2021-06-25
 */
@Service
public class ReplyServiceImpl extends ServiceImpl<ReplyMapper, Reply> implements IReplyService {

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private RedisCache redisCache;

    @Autowired(required = false)
    private ReplyMapper replyMapper;

    @Autowired
    private IReplyInfoService iReplyInfoService;

    @Autowired
    private IGroupInfoService iGroupInfoService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IGroupService iGroupService;

    @Autowired
    private IMessageService iMessageService;


    @Override
    public RestResponse<ReplyResponse> addReply(ReplyAddRequest replyAddRequest) {
        Reply reply = ReplyConvert.INSTANCE.add2Reply(replyAddRequest);
        reply.fillCreateInfo(httpServletRequest, redisCache);
        this.saveOrUpdate(reply);
        HashSet<Long> stuIds = new HashSet<>();
        if (replyAddRequest.getStudentIds() != null) {
            stuIds.addAll(replyAddRequest.getStudentIds());
        }
        if (replyAddRequest.getClazzIds() != null) {
            for (Long clazzId : replyAddRequest.getClazzIds()) {
                List<Long> ids = iUserService.getClassStudentIdsById(clazzId);
                stuIds.addAll(ids);
            }
        }
        if (stuIds.size() == 0) {
            return RestResponse.fail("请添加答辩人员");
        }
        for (Long stuId : stuIds) {
            ReplyInfo replyInfo = new ReplyInfo();
            replyInfo.setReplyId(reply.getId());
            replyInfo.setStudentId(stuId);
            replyInfo.setStatus(ReplyInfoStatus.noSign.getCode());
            replyInfo.fillCreateInfo(httpServletRequest, redisCache);
            iReplyInfoService.saveOrUpdate(replyInfo);
        }
        String title = "您有个新的答辩";
        String content = "您有一个新的答辩：" + reply.getTitle() + "，点击<a href=\"#/student/reply?replyId=" + reply.getId()
                + "\" class=\"\" style=\"color: rgb(64, 158, 255);\"> 查看详情 </a>或在<a href=\"#/student/index\" " +
                "class=\"\" style=\"color: rgb(64, 158, 255);\"> 首页 </a>答辩列表点击进入查看，请及时查看并预约答辩、完成答辩。";
        iMessageService.addMessage(title, content, MessageTypeEnum.notice.getCode(), new ArrayList<>(stuIds));
        return RestResponse.success();
    }

    @Override
    public RestResponse<PageResponse<ReplyResponse>> getCurrentTeacherAllReplys(ReplyPageRequest replyPageRequest) {
        Page<Reply> page = new Page<>(replyPageRequest.getPage(), replyPageRequest.getLimit());
        String token = httpServletRequest.getHeader("Authorization");
        User currentUser = redisCache.getCurrentUser(token);
        Long id = currentUser.getId();
        LambdaQueryWrapper<GroupInfo> qw = new LambdaQueryWrapper<>();
        qw.eq(GroupInfo::getUserId, id);
        List<Long> ids = iGroupInfoService.list(qw).stream().map(GroupInfo::getGroupId).collect(Collectors.toList());
        LambdaQueryWrapper<Reply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Reply::getGroupId, ids);
        if (StringUtils.isNotNullOrBlank(replyPageRequest.getName())) {
            queryWrapper.like(Reply::getTitle, replyPageRequest.getName());
        }
        queryWrapper.orderByAsc(Reply::getId);
        IPage<Reply> pageData = replyMapper.selectPage(page, queryWrapper);
        List<Reply> records = pageData.getRecords();
        List<ReplyResponse> replyResponses = ReplyConvert.INSTANCE.replys2Responses(records);
        for (ReplyResponse replyResponse : replyResponses) {
            Date startTime = replyResponse.getStartTime();
            String format = DateUtils.format(startTime, DateUtils.YYYYMM);
            String config = format.substring(0, 4) + "学年";
            if (Integer.parseInt(format.substring(4)) < 8) {
                config += "春季学期";
            } else {
                config += "秋季学期";
            }
            replyResponse.setConfig(config);
        }
        return RestResponse.success(new PageResponse<>(replyResponses, pageData.getTotal(), replyPageRequest.getPage(), replyPageRequest.getLimit()));
    }

    @Override
    public RestResponse<PageResponse<ReplyResponse>> getCurrentStudentAllReplys(ReplyPageRequest replyPageRequest) {
        Page<Reply> page = new Page<>(replyPageRequest.getPage(), replyPageRequest.getLimit());
        String token = httpServletRequest.getHeader("Authorization");
        User currentUser = redisCache.getCurrentUser(token);
        Long id = currentUser.getId();
        LambdaQueryWrapper<ReplyInfo> qw = new LambdaQueryWrapper<>();
        qw.eq(ReplyInfo::getStudentId, id);
        List<Long> ids = iReplyInfoService.list(qw).stream().map(ReplyInfo::getReplyId).collect(Collectors.toList());
        LambdaQueryWrapper<Reply> queryWrapper = new LambdaQueryWrapper<>();
        if (ids.size() > 0) {
            queryWrapper.in(Reply::getId, ids);
        }
        if (StringUtils.isNotNullOrBlank(replyPageRequest.getName())) {
            queryWrapper.like(Reply::getTitle, replyPageRequest.getName());
        }
        queryWrapper.orderByAsc(Reply::getId);
        IPage<Reply> pageData = replyMapper.selectPage(page, queryWrapper);
        List<Reply> records = pageData.getRecords();
        List<ReplyResponse> replyResponses = ReplyConvert.INSTANCE.replys2Responses(records);
        for (ReplyResponse replyResponse : replyResponses) {
            Date startTime = replyResponse.getStartTime();
            String format = DateUtils.format(startTime, DateUtils.YYYYMM);
            String config = format.substring(0, 4) + "学年";
            if (Integer.parseInt(format.substring(4)) < 8) {
                config += "春季学期";
            } else {
                config += "秋季学期";
            }
            replyResponse.setConfig(config);
        }
        return RestResponse.success(new PageResponse<>(replyResponses, pageData.getTotal(), replyPageRequest.getPage(), replyPageRequest.getLimit()));
    }

    @Override
    public RestResponse<ReplyResponse> getReplyById(Long id) {
        Reply reply = replyMapper.selectById(id);
        if (reply == null) {
            return RestResponse.fail("答辩不存在");
        }
        ReplyResponse replyResponse = ReplyConvert.INSTANCE.reply2Response(reply);
        Date startTime = replyResponse.getStartTime();
        String format = DateUtils.format(startTime, DateUtils.YYYYMM);
        String config = format.substring(0, 4) + "学年";
        if (Integer.parseInt(format.substring(4)) < 8) {
            config += "春季学期";
        } else {
            config += "秋季学期";
        }
        Group group = iGroupService.getById(replyResponse.getGroupId());
        replyResponse.setGroupName(group.getName());
        replyResponse.setConfig(config);
        return RestResponse.success(replyResponse);
    }

}
